package com.nulldev.util.networking.npacket4.demo;

import java.io.IOException;
import java.util.UUID;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.networking.ip.IP;
import com.nulldev.util.networking.npacket4.nPacket;
import com.nulldev.util.networking.npacket4.iprotocols.ncryptx.nCryptRequestKeyPair;
import com.nulldev.util.networking.rudp.Client;
import com.nulldev.util.networking.rudp.Connection;
import com.nulldev.util.networking.rudp.DataReceivedListener;
import com.nulldev.util.networking.rudp.Message;
import com.nulldev.util.networking.rudp.Server;

public class nPacketDemo {

	public static void main(String[] args) {
		final int port = IP.nextFreePort(9000, 13000);
		final Server s = new Server(port, "localhost", 32);
		s.startServer();
		s.registerServerListener(new DataReceivedListener() {

			@Override
			public void receivedMessage(Message message, final Connection connection) {
				JVM.println(message);
				final byte[] o = message.getData();
				try {
					final nPacket np = nPacket.createPacketFromBytes(o);
					switch (np.getPacketID()) {
						case "ncryptx.request_key_pair": {
							final nCryptRequestKeyPair kp = new nCryptRequestKeyPair(np);
							JVM.println("pKey: " + new String(kp.keyPrimary()));
							JVM.println("sKey: " + new String(kp.keySecondary()));
							break;
						}
						default: {
							JVM.println(np);
							break;
						}
					}
				} catch (IOException e) {
					JVM.errorln(e);
				}
			}

			@Override
			public void disconnected(UUID connectionId) {
			}

			@Override
			public void connected(Connection connection) {

			}
		});
		final Client c = new Client(port, "localhost");
		c.startClient();
		c.sendReliablePacket(new nCryptRequestKeyPair(256, 8));
	}

}
